package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.GenerateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: community
 * @BelongsPackage: com.nowcoder.community.controller
 * @Author: Master_XXJS
 * @CreateTime: 2023-01-16  10:39
 * @Description: TODO
 * @Version: 1.0
 */
@Controller
public class ShareController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${wk.image.storage}")
    private String wkImageStorage;
    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;

    /**
     * 生成图片，保存图片到服务器中（本地）
     * @param htmlUrl 需要生成图片的 网址
     * @return
     */
    @RequestMapping(path = "/share", method = RequestMethod.GET)
    @ResponseBody
    public String share(String htmlUrl){
        //生成的文件的文件名，最好使用 UUID，避免名字重复，覆盖名字
        String fileName = GenerateUtil.generateUUID();

        //通过消息队列，实现异步生成长图
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl",htmlUrl)
                .setData("fileName",fileName)
                .setData("suffix",".png");
        eventProducer.fireEvent(event);

        //返回前端，文件的查看的路径，生成图片成功之后，前端也需要进行查看
        Map<String,Object> map = new HashMap<>();
        //本地存储图片的URL
        //map.put("shareUrl",domain + contextPath + "/share/images/" + fileName);

        //七牛云云服务 OSS 存储图片的URL
        map.put("share",shareBucketUrl + "/" + fileName);

        return GenerateUtil.getJsonString(0,null,map);
    }

    //废弃，不需要通过本地进行获取图片了，直接访问七牛云就行了
    // 获取长图
    @RequestMapping(path = "/share/images/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }

        response.setContentType("image/png");
        File file = new File(wkImageStorage + "\\" + fileName + ".png");

        //输出图片到浏览器
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败: " + e.getMessage());
        }
    }
}

